import { User } from './login/model/user';
import { Component,OnInit,Renderer,ElementRef,ViewContainerRef} from '@angular/core';
import { ActivatedRoute, Router, ActivatedRouteSnapshot, RouterState, RouterStateSnapshot } from '@angular/router';
import {NzMessageService} from 'ng-zorro-antd';
import {UserLoginService} from './login/loginservice/login.service';
import 'rxjs/add/operator/merge';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
    public currentUser:User;
    public isCollapsed:boolean=false;  //默认左侧导航条是打开的
    public currentStyles:any= {};
    private globalClickFun:Function;
    
    public test:string="登录";

  constructor(
    public nzMsg:NzMessageService,
    public renderer:Renderer,
    public elementRef:ElementRef,
    public loginservice:UserLoginService,

    public router:Router,
    public activateRoute:ActivatedRoute,
  ){

  }

  /**
   * 全局监听用户是否登录
   * 引入oninit后ngOninit事件没有触发，不知道什么原因
   * @memberof AppComponent
   */
  ngOnInit(){
    this.globalClickFun=this.renderer.listen(this.elementRef.nativeElement,'click',(event)=>{
      console.log("-----全局监听事件------");
      console.log(this.elementRef.nativeElement);
      console.log(event);
      console.log("-----全局监听结束------");
    });
    
    this.currentUser=JSON.parse(localStorage.getItem("currentUser"));
    console.log(this.currentUser);
    this.loginservice.currentUser
        // .map(data=>{
        //   //测试
        //   this.currentUser.vcode="1234";
        //   return this.currentUser;
        // })
        .subscribe(
          data=>{
            this.currentUser=data;
            let activatedRouteSnapshot:ActivatedRouteSnapshot=this.activateRoute.snapshot;
            let routerState:RouterState=this.router.routerState;
            let routerStateSnapshot:RouterStateSnapshot=routerState.snapshot;

            console.log("-----输出路由的各种值查看区别-----")
            console.log(activatedRouteSnapshot);
            console.log(routerState);
            console.log(routerStateSnapshot);
            //
            if(routerStateSnapshot.url.indexOf("/login")>=0){
              console.log("非法登录");
              this.router.navigateByUrl("/home");
            }
          },
          error=>{
            console.error(error);
          }
        )

  }

  showMsg():void{
    this.nzMsg.info("退出成功",{nzDuration:2000});
  }

  //导航条收缩/打开之间切换的样式处理
  updateMarginLeft(elm1:any,elm2:any){
      this.isCollapsed=!this.isCollapsed;  
      let leftSize:number=0;    
      if(!this.isCollapsed){
        leftSize=(Number(elm1.nzWidth)-elm2._el.offsetWidth)/2;
      }
      else{
        leftSize=(Number(elm1.nzCollapsedWidth)-elm2._el.offsetWidth)/2;
      }
      this.currentStyles={
        'margin-left':leftSize+'px',
      }

  }

  logout(){
    this.loginservice.logOut();
    this.showMsg();
    this.router.navigateByUrl("/login");
  }
}
